'use strict';

const RouterService = require('../base');

class BiddingSupplierService extends RouterService {
  static get modelName() {
    return 'Business.BiddingSupplier';
  }

  getListInclude() {
    return [
      {
        model: this.ctx.model.Business.Supplier,
        as: 'supplier',
      },
      {
        model: this.ctx.model.Business.SupplierQuote,
        as: 'supplierQuotes',
        include: [
          {
            model: this.ctx.model.Business.Dish,
            as: 'dish'
          }
        ]
      }
    ]
  }

  async beforeCreate(data) {
    const { monthly_bidding_id, supplier_id } = data;
    const monthlyBidding = await this.ctx.model.Business.MonthlyBidding.findByPk(monthly_bidding_id);
    if (!monthlyBidding) {
      throw new Error('月度比价不存在');
    }
    if (monthlyBidding.status !== 2) {
      throw new Error('非月度比价进行状态，无法加入供应商');
    }
    const supplier = await this.ctx.model.Business.Supplier.findByPk(supplier_id);
    if (!supplier) {
      throw new Error('供应商不存在');
    }
    const biddingSupplier = await this.ctx.model.Business.BiddingSupplier.findOne({
      where: {
        monthly_bidding_id,
        supplier_id
      }
    });
    if (biddingSupplier) {
      throw new Error('供应商已加入');
    }
    return data;
  }
}

module.exports = BiddingSupplierService;
